package com.neuedu.web.service;

import com.neuedu.web.common.PageInfo;
import com.neuedu.web.dao.DeptDao;
import com.neuedu.web.dao.RegistLevelDao;
import com.neuedu.web.dao.UmsUserDao;
import com.neuedu.web.dao.UserRoleDao;
import com.neuedu.web.po.RegistLevelPO;
import com.neuedu.web.po.UmsUser;
import com.neuedu.web.po.UserRolePO;
import com.neuedu.web.utils.BeanConvertUtils;
import com.neuedu.web.utils.ParamUtils;
import com.neuedu.web.vo.UserVO;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 金山
 * 项目：javaweb
 * site: https://blog.fulfill.com.cn
 * 描述
 * @data 2024/11/1815:55
 */
public class UserService {
    private UmsUserDao userDao = new UmsUserDao();
    private DeptDao deptDao = new DeptDao();
    private RegistLevelDao levelDao = new RegistLevelDao();
    private UserRoleDao userRoleDao = new UserRoleDao();


    public List list(HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchFieldException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {


        String sql = " select * from ums_user";
        List<UmsUser> umsUsers = userDao.selectAll(sql);

        List userVOList = umsUsers.stream().map(umsUser -> {

            UserVO userVo = BeanConvertUtils.conver(UserVO.class, umsUser);
            return BeanConvertUtils.conver(UserVO.class, umsUser);
        }).collect(Collectors.toList());

        // Map result = new HashMap();
        // result.put("code",200);
        // result.put("msg","");
        // result.put("data",userVOList);

        // JSONUtils.write(response, Res.ok(userVOList));


        return userVOList;

    }

    public boolean delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");

        int count = userDao.delete(Long.parseLong(id));

        return count > 0;
        // if(count >0){
        //     JSONUtils.write(response,Res.ok(true));
        // }else{
        //     JSONUtils.write(response,Res.ok(false));
        //
        // }
    }

    public boolean save(HttpServletRequest request, HttpServletResponse response) {


        // UmsUser user = new UmsUser();
        // String username = request.getParameter("username");
        // String password = request.getParameter("password");
        // String nickname = request.getParameter("username");
        //
        // user.setUsername(username);
        // user.setPassword(password);
        // user.setNickname(nickname);

        UmsUser user = ParamUtils.getParam(UmsUser.class, request);

        if (user.getUserid() != null) {
            return userDao.update(user) > 0;
        } else {
            return userDao.insert(user) > 0;
        }

    }

    public PageInfo<UmsUser> page(HttpServletRequest request, HttpServletResponse response) throws NoSuchFieldException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {


        // String sql = " select * from ums_user" ;


        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT ");
        sql.append(" u.*, lev.`caption` level_name ");
        sql.append("        FROM   ");
        sql.append(" ums_user u LEFT JOIN regist_level lev ");
        sql.append(" ON u.`regist_level` = lev.`level_id` ");

        System.out.println("sql.toString() = " + sql.toString());
        PageInfo pageInfo = ParamUtils.getPageInfo(request);
        List<UmsUser> umsUsers = userDao.selectPage(pageInfo.getCurrent(), pageInfo.getSize(), sql.toString());
        int total = userDao.total(sql.toString());

        pageInfo.setTotal(total);

        List userVOList = umsUsers.stream().map(umsUser -> {

            return BeanConvertUtils.conver(UserVO.class, umsUser);
        }).collect(Collectors.toList());

        pageInfo.setData(userVOList);

        return pageInfo;

    }

    public UmsUser getById(HttpServletRequest request, HttpServletResponse response) throws NoSuchFieldException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        String id = request.getParameter("id");

        return userDao.selectById(Long.parseLong(id));
    }

    public Map initPage(HttpServletRequest request, HttpServletResponse response) throws NoSuchFieldException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        Map map = new HashMap();

        map.put("deptList", deptDao.selectAll("select * from dept "));
        map.put("levelList", levelDao.selectAll(RegistLevelPO.class, "select * from regist_level"));

        return map;
    }


    /**
     * 接受所有的用户你和角色
     * @param request
     * @param response
     * @return
     */
    public boolean grant(HttpServletRequest request, HttpServletResponse response) {


        String userid = request.getParameter("userid");   //3
        String strRoleIds = request.getParameter("roleIds"); // "1,2"

        String roleIds[] = strRoleIds.split(",");
        int count = 0;


        //删除用于已经授权 的角色
        int deleteUserCount = userRoleDao.deleteByUserId(userid);

        for (String roleId : roleIds) {
            UserRolePO po = new UserRolePO();
            po.setUserid(Long.parseLong(userid));;
            po.setRoleId(Long.parseLong(roleId));
            count += userRoleDao.insert(po);
        }

        return  roleIds.length == count;
    }
}
